
<template>
  <div>
    <el-autocomplete
        v-model="names"
        :fetch-suggestions="querySearch"
        :trigger-on-focus="false"
        clearable
        placeholder="请输入您要搜索的商品名"
        @select="handleSelect"
        style="width:270px"
    />
    <el-button style="margin-left: 10px">搜索</el-button>
  </div>
</template>

<script scope setup>

// import axios from "axios";


import {productNameService} from "@/api/product";
import {ref} from "vue";
const names=ref('')
const  restaurants = ref()
const querySearch=(queryString, cb)=>{
  if(restaurants.value===''){return }
       const results = queryString ? restaurants.value.filter(createFilter(queryString)) : restaurants
       // call callback function to return suggestions
      cb(results)
}
const createFilter=(queryString)=>{
       return (restaurant) => {
         return (
             // restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) == 0
             /*index==0表示是否在第一个索引位置找到输入的字符，*/
             restaurant.value.indexOf(queryString) != -1 //这个语句表示只有有关键字即可，不论在哪个位置匹配到

         )
       }
     }
     //输入选定的值
    const handleSelect=(item)=>{
       // console.log(item)
     }

const takeNames = async ()=>{
  if (names.value!=='') {
    let result = await productNameService(names.value)
    let restaurantObjects = result.data.map(name => ({ value: name }));
    restaurants.value = restaurantObjects
  }
}
setInterval(takeNames, 5000);

</script>
<style scoped>
</style>